package fun.boomcat.luckyhe.mirai.plugin.command.utils.thread;

import fun.boomcat.luckyhe.mirai.plugin.bean.Reply;
import fun.boomcat.luckyhe.mirai.plugin.bean.ReplyState;
import fun.boomcat.luckyhe.mirai.plugin.config.ConfigOperation;
import fun.boomcat.luckyhe.mirai.plugin.dbutils.ReplyListModifier;
import net.mamoe.mirai.console.command.CommandSender;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class ReplyWebThread implements Runnable {
    private static ServerSocket serverSocket;
    private static String outputString = "";

    public static String httpFrame(String title, List<Reply> replies, boolean withHead) {
//        http显示框架，内容由外部传入

        StringBuilder sb = new StringBuilder();
        if (withHead) {
            sb.append("HTTP/1.1 200 OK\n");
            sb.append("Content‐Type:text/html\n\n");
        }
        sb.append("<!DOCTYPE html>");

        sb.append("<html>");
        sb.append("<head><title>查询结果</title></head>");

        sb.append("<body>");

        sb.append("<h1 align=\"center\">").append(title).append("</h1>");
        sb.append("<table align=\"center\" cellpadding=\"5\"style=\"border: 1px solid black;\">");
        sb.append("<tr>").append("<th>ID</th>").append("<th>QQ</th>").append("<th>类型</th>")
                .append("<th>状态</th>").append("<th>关键字</th>").append("<th>回复/替换</th>").append("</tr>");

        for (Reply reply : replies) {
            sb.append("<tr>");

            sb.append("<td align=\"center\">").append(reply.getId()).append("</td>");
            sb.append("<td align=\"center\">").append(reply.getQq()).append("</td>");
            sb.append("<td align=\"center\">").append(reply.getType().getName()).append("</td>");
            sb.append("<td align=\"center\">").append(reply.getReplyState().getName()).append("</td>");
            sb.append("<td>").append(reply.getKeyword().replaceAll(" ", "&nbsp;").replaceAll("\\n", "<br/>")).append("</td>");
            sb.append("<td>").append(reply.getReply().replaceAll(" ", "&nbsp;").replaceAll("\\n", "<br/>")).append("</td>");

            sb.append("</tr>");
        }

        if (replies.size() == 0) {
            sb.append("<h1 align=\"center\">").append("好像没有添加过回复哦").append("</h1>");
        }

        sb.append("</table>");
        sb.append("</body>");
        sb.append("</html>");

        return sb.toString();
    }

    public static void showUserRepliesWeb(Long qq, CommandSender commandSender, boolean hasHideDeleted) throws IOException {
//        显示用户回答

        List<Reply> replyList = ReplyListModifier.selectRepliesByQq(qq);
        if (hasHideDeleted) {
//            如果为true，表示不显示已删除项目

            List<Reply> newReplyList = new ArrayList<>();
            for (Reply reply : replyList) {
                if (!reply.getReplyState().equals(ReplyState.DELETED)) {
                    newReplyList.add(reply);
                }
            }
            replyList = newReplyList;
        }

        outputString = httpFrame(
                "用户" + qq + "的自动回复",
                replyList,
                true
        );
    }

    public static void showAllRepliesWeb(CommandSender commandSender) throws IOException {
//        显示所有回复

        List<Reply> replyList = ReplyListModifier.selectAllReplies();
        outputString = httpFrame("所有回复", replyList, true);
    }

    public static void showAuditingRepliesWeb(CommandSender commandSender) throws IOException {
//        显示审核中回复

        StringBuilder sb = new StringBuilder();

        List<Reply> replyList = ReplyListModifier.selectAuditingReplies();

        outputString = httpFrame("待审核自动回复", replyList, true);
    }

    public static void showSelectedUserRepliesWeb(CommandSender commandSender, List<Long> qqList) throws IOException {
//        显示选择的用户的所有回复

        StringBuilder sb = new StringBuilder();

        boolean withHead = true;
        for (Long qq : qqList) {
            List<Reply> replyList = ReplyListModifier.selectRepliesByQq(qq);
            sb.append(httpFrame("用户" + qq + "添加的自动回复", replyList, withHead));
            withHead = false;
        }

        outputString = sb.toString();
    }

    static {
//        当类被使用时执行此代码块

        boolean flag = true;
        while (flag) {
            try {
                int port = Integer.parseInt(ConfigOperation.getWebsiteInifo().get("port"));
                serverSocket = new ServerSocket(port);
                flag = false;
            } catch (Exception ignored) {

            }
        }

        Thread replyWebThread = new Thread(new ReplyWebThread());
        replyWebThread.setDaemon(true);
        replyWebThread.start();
    }

    @Override
    public void run() {
//        守护线程

        while (true) {
            try {
                Socket socket = serverSocket.accept();
//                String system = System.getProperty("os.name").toLowerCase();

                BufferedWriter bw = new BufferedWriter(
                        new OutputStreamWriter(socket.getOutputStream(), "GBK")
                );
                bw.write(outputString);
                bw.flush();
                bw.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
